﻿using Google.Protobuf.WellKnownTypes;
using Grpc.Core;
using Microsoft.AspNetCore.Razor.TagHelpers;

namespace Zhy.gRPCDemo.DefaultServer.Services
{
    public class AdvancedgreetService : AdvancedGreeter.AdvancedGreeterBase
    {
        /// <summary>
        /// 有请求参数有返回参数
        /// </summary>
        /// <param name="request"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public override async Task<HelloReplyMath> SayHello(HelloRequestMath request, ServerCallContext context)
        {
            //return base.SayHello(request, context);
            return await Task.FromResult<HelloReplyMath>(new HelloReplyMath()
            {
                Message = $"this is {request.Id}=={request.Name}"
            }); ;

        }


        /// <summary>
        /// 支持客户端流
        /// </summary>
        /// <param name="requestStream">客户端流参数</param>
        /// <param name="context">服务连接对象</param>
        /// <returns></returns>
        public override async Task<IntArrayModel> SelfIncreaseClient(IAsyncStreamReader<BathTheCatReq> requestStream, ServerCallContext context)
        {
            //IntArrayModel: 多个对象打包对象
            IntArrayModel intArrayModel = new IntArrayModel();
            while (await requestStream.MoveNext()) // 循环读取客户端流
            {
                intArrayModel.Number.Add(requestStream.Current.Id + 1); // 添加到集合
                Console.WriteLine($"SelfIncreaseClient Number {requestStream.Current.Id} 获取到并处理.");
                Thread.Sleep(100);
            }
            return intArrayModel;
        }


        /// <summary>
        /// 支持服务端流
        /// </summary>
        /// <param name="request"></param>
        /// <param name="responseStream">服务端流对象</param>
        /// <param name="context"></param>
        /// <returns></returns>
        public override async Task SelfIncreaseServer(IntArrayModel request, IServerStreamWriter<BathTheCatResp> responseStream, ServerCallContext context)
        {
            foreach (var item in request.Number)
            {
                int number = item;
                Console.WriteLine($"This is {number} invoke");

                await responseStream.WriteAsync(new BathTheCatResp()  // 服务端返回多个结果对象。
                {
                    Message = $"number+={number}"
                });
                //Thread.Sleep(500);
                await Task.Delay(500);
            }
        }

        /// <summary>
        ///双向流
        /// </summary>
        /// <param name="requestStream">客户端流</param>
        /// <param name="responseStream">服务端流</param>
        /// <param name="context"></param>
        /// <returns></returns>
        public override async Task SelfIncreaseDouble(IAsyncStreamReader<BathTheCatReq> requestStream, IServerStreamWriter<BathTheCatResp> responseStream, ServerCallContext context)
        {
            while (await requestStream.MoveNext())
            {
                Console.WriteLine($"SelfIncreaseDouble Number {requestStream.Current.Id} 获取到并处理.");
                await responseStream.WriteAsync(new BathTheCatResp() { Message = $"number++ ={requestStream.Current.Id + 1}！" });
                await Task.Delay(500);//此处主要是为了方便客户端能看出流调用的效果
            }
        }

        /// <summary>
        /// 空参数
        /// </summary>
        /// <param name="request">空参数</param>
        /// <param name="context"></param>
        /// <returns></returns>
        public override async Task<CountResult> Count(Empty request, ServerCallContext context)
        {

            Console.WriteLine("乜有任何参数, 请求来了~~");
            return await Task.FromResult(new CountResult()
            {
                Count = 1
            });
        }

        /// <summary>
        /// 接收单元端图像
        /// </summary>
        /// <param name="requestStream"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public override async Task<UploadFileResp> UploadFile(IAsyncStreamReader<UploadFileReq> requestStream, ServerCallContext context)
        {
            try
            {
                FileStream fileStream = null;
                var dir = AppDomain.CurrentDomain.BaseDirectory; // 获取程序根目录
                dir = $@"{dir}\grpcImage";
                var filePath = "";
                var next = await requestStream.MoveNext(); // 获取读取器下一步结果-有结果范围true 没有结果返回false
                filePath = Path.Combine(dir, requestStream.Current.FileName); // 拼接图像保存路径
                if (requestStream.Current.FileName.StartsWith("\\"))
                {
                    filePath = dir + requestStream.Current.FileName; // 拼接图像保存路径
                }
                string strUrl = Path.GetDirectoryName(filePath); // 获取指定目录信息
                if (!Directory.Exists(strUrl))
                    Directory.CreateDirectory(strUrl); //创建了文件夹之后，才能创建里面的文件
                while (next) // 循环读取图像流数据
                {
                    if (fileStream == null)
                    {
                        fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write); // 创建图像
                    }
                    var array = requestStream.Current.FileChunk.ToByteArray(); // 读取图像流
                    fileStream.Write(array, 0, array.Length); // 写入图像流
                    next = await requestStream.MoveNext(); // 等待读取下一次流
                }

                fileStream?.Dispose(); // 释放流资源
                return new UploadFileResp() { FileName = filePath }; // 返回图像路径
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            return new UploadFileResp() { FileName = null };
        }
    }
}
